//
//  HDStartLearningViewController.m
//  HDecoration
//
//  Created by 曹群 on 15/8/16.
//  Copyright (c) 2015年 HDecoration. All rights reserved.
//

#import "HDStartLearningViewController.h"

@interface HDStartLearningViewController ()
@property(nonatomic,strong)UITableView *contentTableView;
@property(nonatomic,strong)DOImageView *photo;
@property(nonatomic,strong)UILabel *nameLabel;
@property(nonatomic,strong)UILabel *stationTimeLabel;
@property(nonatomic,strong)UILabel *typeLabel;
@property(nonatomic,strong)UILabel *learnTimeLabel;
@property(nonatomic,strong)UILabel *remarkLabel;
@property(nonatomic,strong)GXButton *callBtn;
@property(nonatomic,strong)GXButton *locationBtn;
@property(nonatomic,strong)UILabel *subjectLabel;
@property(nonatomic,strong)UIButton *startTimerBtn;
@property(nonatomic,strong)UIButton *finishBtn;
@property(nonatomic,strong)UITextView *finishTextView;
@property(nonatomic,strong)UIButton *confirmBtn;
@property(nonatomic,assign)int timeInterval;
@property(nonatomic,assign)BOOL finished;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,assign)double startTime;
@property CGPoint activePoint;
@end

@implementation HDStartLearningViewController

- (void)initUI {
    self.view.backgroundColor = kContentViewColor;
    [self.view addSubview:self.contentTableView];
    [self registerForKeyboardNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkInput) name:UITextViewTextDidChangeNotification object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)checkInput
{
    self.confirmBtn.enabled = self.finishTextView.text.length;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.timer invalidate];
}

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(textBeginEditing:)
                                                name:UITextViewTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(textBeginEditing:)
                                                name:UITextFieldTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(checkInput)
                                                name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)textBeginEditing:(NSNotification*)aNotification
{
    UIView* sender=[aNotification object];
    CGRect rect=sender.frame;
    rect.origin.y+=rect.size.height;
    self.activePoint=[[sender superview] convertPoint:rect.origin toView:self.contentTableView];
    self.activePoint=[self.contentTableView convertPoint:self.activePoint toView:self.contentTableView];
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    kbSize.height+=30;
    
    float hiddenH=self.contentTableView.frame.size.height-(self.contentTableView.frame.size.height-kbSize.height);
    
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0,hiddenH, 0.0);
    self.contentTableView.contentInset = contentInsets;
    self.contentTableView.scrollIndicatorInsets = contentInsets;
    float activeH=self.contentTableView.frame.size.height-self.activePoint.y;
    if(kbSize.height>activeH)
    {
        float dif=activeH-kbSize.height;
        CGPoint scrollPoint = CGPointMake(0.0,0-dif);
        [self.contentTableView setContentOffset:scrollPoint animated:YES];
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    [UIView animateWithDuration:0.3 animations:^{
        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        self.contentTableView.contentInset = contentInsets;
        self.contentTableView.scrollIndicatorInsets = contentInsets;
    }];
}

#pragma mark - UITableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row==0) {
            UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, APPFRAME.size.width, 0.5)];
            line.image = [UIImage imageNamed:@"dot"];
            [cell.contentView addSubview:line];
            [cell.contentView addSubview:self.photo];
            [cell.contentView addSubview:self.nameLabel];
            [cell.contentView addSubview:self.stationTimeLabel];
            [cell.contentView addSubview:self.typeLabel];
            if (self.orderType==HDOrderTypeLearn) {
                [cell.contentView addSubview:self.subjectLabel];
            }
        } else if (indexPath.row==1) {
            UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, APPFRAME.size.width, 0.5)];
            line.image = [UIImage imageNamed:@"dot"];
            [cell.contentView addSubview:line];
            [cell.contentView addSubview:self.learnTimeLabel];
            if (self.orderType==HDOrderTypePractice) {
                [cell.contentView addSubview:self.remarkLabel];
            } else {
                [cell.contentView addSubview:self.locationBtn];
            }
        }
    }
    if (indexPath.row==0) {
        if (self.finished) {
            UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(self.callBtn.left-5, 20, 0.5, 45)];
            line.image = [UIImage imageNamed:@"dot"];
            [cell.contentView addSubview:line];
            [cell.contentView addSubview:self.callBtn];
            if (self.orderType==HDOrderTypeLearn) {
                self.subjectLabel.left = APPFRAME.size.width-130;
            }
        }
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, APPFRAME.size.width, 300)];
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, APPFRAME.size.width, 0.5)];
    line.image = [UIImage imageNamed:@"dot"];
    [footerView addSubview:line];
    if (!self.finished) {
        [footerView addSubview:self.startTimerBtn];
        NSArray *titleArr = @[@"开始时间:",@"计       时:",@"结束时间:"];
        for (int i=0; i<3; i++) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, self.startTimerBtn.bottom+10+40*i, APPFRAME.size.width/2.0-20, 40)];
            label.font = [UIFont systemFontOfSize:20];
            label.textColor = [UIColor hexStringToColor:@"#424242"];
            label.textAlignment = NSTextAlignmentRight;
            label.text = titleArr[i];
            label.tag = 100+i;
            label.hidden = YES;
            [footerView addSubview:label];
            UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(APPFRAME.size.width/2.0, self.startTimerBtn.bottom+10+40*i, APPFRAME.size.width/2.0, 40)];
            contentLabel.font = [UIFont systemFontOfSize:20];
            contentLabel.textColor = [UIColor hexStringToColor:@"#e94929"];
            contentLabel.tag = 200+i;
            [footerView addSubview:contentLabel];
        }
    } else {
        [footerView addSubview:self.finishBtn];
        [footerView addSubview:self.finishTextView];
        [footerView addSubview:self.confirmBtn];
    }
    
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 80;
    } else if (indexPath.row==1) {
        return 70;
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 300;
}

#pragma mark - actions
- (void)startTimer:(UIButton *)sender
{
    
    NSDictionary* params=@{
                            @"id":self.customerInfo.order_id,//订单id
                           };
    [netEngine RequestStartLessonWithTarget:self.VctrID hudView:self.contentView Data:params];
}

- (void)refreshTime:(NSTimer *)timer
{
    _timeInterval++;
    NSString *timerStr = [NSString stringWithFormat:@"%02d:%02d:%02d",_timeInterval/3600,_timeInterval%3600/60,_timeInterval%3600%60];
    UILabel *timeLabel = (UILabel *)[self.contentTableView viewWithTag:201];
    timeLabel.text = timerStr;
    if (_timeInterval>=[self.customerInfo.learnTime intValue]*3600)
    {
        self.finished = YES;
        [self.timer invalidate];
    }
}

-(void)updateViewController:(NSNotification *)note
{
    NSDictionary* dic=note.userInfo;
    if ([dic objectForKey:Receiver]==self.VctrID)
    {
        if (dic[@"ServerTime"]!=nil)
        {
            self.startTime = [dic[@"currentTime"] longLongValue];
        }
        else if (dic[@"StartLesson"]!=nil)
        {
            self.startTime = [dic[@"startTime"] longLongValue];
        }
        else if (dic[@"LessonStatus"]!=nil)
        {
            if ([dic[@"code"] intValue]==0)
            {
                self.startTimerBtn.enabled = YES;
            }
            else if ([dic[@"code"] intValue]==200)
            {
                self.startTime = [dic[@"startTime"] longLongValue];
            }
            else if ([dic[@"code"] intValue]==-1)
            {
                self.startTimerBtn.enabled = NO;
                [netEngine showErrorAlertWithMsg:dic[@"message"]];
            }
            else if ([dic[@"code"] intValue]==-2)
            {
                self.startTimerBtn.enabled = NO;
                [netEngine showErrorAlertWithMsg:dic[@"message"]];
            }
        }
        else if (dic[@"EndConfirm"]!=nil)
        {
            [rootNavigation popViewControllerAnimated:YES];
        }
    }
}

- (void)confirmAction:(UIButton *)sender
{
    double endTime = self.startTime+[self.customerInfo.endTime doubleValue]-[self.customerInfo.startTime doubleValue];
    [netEngine RequestEndConfirmWithTarget:self.VctrID hudView:self.view Data:@{@"s_order":self.customerInfo.order_id,
                                                                                @"endTime":[NSNumber numberWithDouble:endTime],
                                                                                @"content":[HDUtil check:self.finishTextView.text]}];
}

- (void)callAction:(UIButton *)sender
{
    [HDUtil call:[HDUtil check:self.customerInfo.phoneNumber]];
}

#pragma mark - setters
- (void)setCustomerInfo:(HDCustomerInfo *)customerInfo
{
    _customerInfo = [customerInfo copy];
    self.photo.imgURLStr = _customerInfo.photoUrl;
    self.nameLabel.text = _customerInfo.name;
    self.stationTimeLabel.text = [NSString stringWithFormat:@"平台学时：%@",_customerInfo.stationTime];
    self.typeLabel.text = [NSString stringWithFormat:@"驾考类型：%@",_customerInfo.type];
    if (_customerInfo.startTime!=nil&&_customerInfo.endTime!=nil) {
        NSString *date = [HDUtil formatter:@"M月d日" FromTime:[_customerInfo.startTime doubleValue]];
        NSString *startTime = [HDUtil formatter:@"HH:mm" FromTime:[_customerInfo.startTime doubleValue]];
        NSString *endTime = [HDUtil formatter:@"HH:mm" FromTime:[_customerInfo.endTime doubleValue]];
        self.learnTimeLabel.text = [NSString stringWithFormat:@"学车时间：%@ %@-%@ %@个小时",date,startTime,endTime,[HDUtil check:_customerInfo.learnTime]];
    }
    if (self.orderType==HDOrderTypePractice) {
        self.remarkLabel.text = [NSString stringWithFormat:@"备注：%@",_customerInfo.remark];
    } else {
        if (_customerInfo.location.length) {
            [self.locationBtn setImage:[UIImage imageNamed:@"定位"] forState:UIControlStateNormal];
            [self.locationBtn setTitle:_customerInfo.location forState:UIControlStateNormal];
        }
        self.subjectLabel.text = _customerInfo.subject;
    }
    
    [netEngine RequestLessonStatusWithTarget:self.VctrID hudView:self.view Data:@{@"id":_customerInfo.order_id}];
}

- (void)setFinished:(BOOL)finished
{
    _finished = finished;
    self.navigationItem.title = @"课程结束";
    [self.contentTableView reloadData];
    [netEngine startBroadcast:@"课程时间已完毕"];
}

- (void)setStartTime:(double)startTime
{
    _startTime = startTime;
    self.startTimerBtn.enabled = NO;
    for (int i=100; i<103; i++)
    {
        UILabel *titleLabel = (UILabel *)[self.contentTableView viewWithTag:i];
        titleLabel.hidden = NO;
    }
    NSDate *endDate = [NSDate dateWithTimeInterval:[self.customerInfo.learnTime intValue]*3600 sinceDate:[NSDate dateWithTimeIntervalSince1970:_startTime/1000]];
    NSString *currentTime = [HDUtil formatter:@"HH:mm:ss" FromTime:_startTime];
    NSString *endTime = [HDUtil formatter:@"HH:mm:ss" FromeDate:endDate];
    UILabel *currentTimeLabel = (UILabel *)[self.contentTableView viewWithTag:200];
    currentTimeLabel.text = currentTime;
    UILabel *endTimeLabel = (UILabel *)[self.contentTableView viewWithTag:202];
    endTimeLabel.text = endTime;
    _timeInterval=[endDate timeIntervalSinceNow];
    _timeInterval=[self.customerInfo.learnTime intValue]*3600-_timeInterval;
    [self refreshTime:nil];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshTime:) userInfo:nil repeats:YES];
}

#pragma mark - getters
- (UITableView *)contentTableView
{
    if (!_contentTableView) {
        _contentTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 74, APPFRAME.size.width, APPFRAME.size.height-54) style:UITableViewStyleGrouped];
        _contentTableView.delegate = (id)self;
        _contentTableView.dataSource = (id)self;
        _contentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _contentTableView.bounces = NO;
        _contentTableView.backgroundColor = [UIColor whiteColor];
    }
    return _contentTableView;
}

- (DOImageView *)photo
{
    if (!_photo) {
        _photo = [[DOImageView alloc] initWithFrame:CGRectMake(10, 15, 50, 50)];
        _photo.layer.cornerRadius = 5;
        _photo.layer.masksToBounds = YES;
        _photo.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _photo;
}

- (UILabel *)nameLabel
{
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.photo.right+15, 15, 100, 20)];
        _nameLabel.font = [UIFont systemFontOfSize:15];
        _nameLabel.textColor = kDarkGrayColor;
    }
    return _nameLabel;
}

- (UILabel *)stationTimeLabel
{
    if (!_stationTimeLabel) {
        _stationTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.photo.right+15, self.nameLabel.bottom, APPFRAME.size.width-130, 15)];
        _stationTimeLabel.font = [UIFont systemFontOfSize:12];
        _stationTimeLabel.textColor = [UIColor hexStringToColor:@"#424242"];
    }
    return _stationTimeLabel;
}

- (UILabel *)typeLabel
{
    if (!_typeLabel) {
        _typeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.photo.right+15, self.stationTimeLabel.bottom, APPFRAME.size.width-130, 15)];
        _typeLabel.font = [UIFont systemFontOfSize:12];
        _typeLabel.textColor = kLightGrayColor;
    }
    return _typeLabel;
}

- (UILabel *)learnTimeLabel
{
    if (!_learnTimeLabel) {
        _learnTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, APPFRAME.size.width-20, 15)];
        _learnTimeLabel.font = [UIFont systemFontOfSize:13];
        _learnTimeLabel.textColor = kDarkGrayColor;
    }
    return _learnTimeLabel;
}

- (UILabel *)remarkLabel
{
    if (!_remarkLabel) {
        _remarkLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, self.learnTimeLabel.bottom+10, APPFRAME.size.width-95, 15)];
        _remarkLabel.font = [UIFont systemFontOfSize:13];
        _remarkLabel.textColor = kDarkGrayColor;
    }
    return _remarkLabel;
}

- (GXButton *)callBtn
{
    if (!_callBtn) {
        _callBtn = [GXButton buttonWithType:UIButtonTypeCustom];
        _callBtn.frame = CGRectMake(APPFRAME.size.width-50, 20, 40, 40);
        _callBtn.imageViewFrame = CGRectMake(2.5, 2.5, 35, 35);
        _callBtn.relayout = YES;
        [_callBtn setImage:[UIImage imageNamed:@"电话"] forState:UIControlStateNormal];
        [_callBtn addTarget:self action:@selector(callAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _callBtn;
}

- (GXButton *)locationBtn
{
    if (!_locationBtn) {
        _locationBtn = [GXButton buttonWithType:UIButtonTypeCustom];
        _locationBtn.frame = CGRectMake(10, self.learnTimeLabel.bottom+10, APPFRAME.size.width-20, 20);
        _locationBtn.imageViewFrame = CGRectMake(5, 3, 9, 13);
        _locationBtn.titleLabelFrame = CGRectMake(23, 0, APPFRAME.size.width-43, 20);
        [_locationBtn setTitleColor:kDarkGrayColor forState:UIControlStateNormal];
        _locationBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        _locationBtn.relayout = YES;
        _locationBtn.userInteractionEnabled = NO;
    }
    return _locationBtn;
}

- (UILabel *)subjectLabel
{
    if (!_subjectLabel) {
        _subjectLabel = [[UILabel alloc] initWithFrame:CGRectMake(APPFRAME.size.width-60, 15, 50, 20)];
        _subjectLabel.font = [UIFont systemFontOfSize:14];
        _subjectLabel.textColor = kDarkGrayColor;
    }
    return _subjectLabel;
}

- (UIButton *)startTimerBtn
{
    if (!_startTimerBtn) {
        _startTimerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _startTimerBtn.frame = CGRectMake(20, 30, APPFRAME.size.width-40, 44);
        [_startTimerBtn setBackgroundImage:[UIImage imageNamed:@"登录"] forState:UIControlStateNormal];
        [_startTimerBtn setTitle:@"开始计时" forState:UIControlStateNormal];
        _startTimerBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_startTimerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_startTimerBtn addTarget:self action:@selector(startTimer:) forControlEvents:UIControlEventTouchUpInside];
        _startTimerBtn.enabled = NO;
    }
    return _startTimerBtn;
}

- (UIButton *)finishBtn
{
    if (!_finishBtn) {
        _finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _finishBtn.frame = CGRectMake(60, 30, APPFRAME.size.width-120, 44);
        [_finishBtn setBackgroundImage:[UIImage imageNamed:@"课时完成"] forState:UIControlStateNormal];
        [_finishBtn setTitle:@"课时已完成，本课结束" forState:UIControlStateNormal];
        _finishBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_finishBtn setTitleColor:[UIColor hexStringToColor:@"#e94929"] forState:UIControlStateNormal];
        _finishBtn.userInteractionEnabled = NO;
    }
    return _finishBtn;
}

- (UITextView *)finishTextView
{
    if (!_finishTextView) {
        _finishTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, self.finishBtn.bottom+10, APPFRAME.size.width-10, 100)];
        _finishTextView.font = [UIFont systemFontOfSize:15];
        _finishTextView.backgroundColor = kContentViewColor;
        _finishTextView.layer.cornerRadius = 5;
    }
    return _finishTextView;
}

- (UIButton *)confirmBtn
{
    if (!_confirmBtn) {
        _confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _confirmBtn.frame = CGRectMake(20, self.finishTextView.bottom+20, APPFRAME.size.width-40, 44);
        [_confirmBtn setBackgroundImage:[UIImage imageNamed:@"登录"] forState:UIControlStateNormal];
        [_confirmBtn setTitle:@"请求学员确认" forState:UIControlStateNormal];
        _confirmBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_confirmBtn addTarget:self action:@selector(confirmAction:) forControlEvents:UIControlEventTouchUpInside];
        _confirmBtn.enabled = NO;
    }
    return _confirmBtn;
}

@end
